package cn.tedu.charging.account.controller;

import cn.tedu.charging.account.pojo.param.UserAddNewParam;
import cn.tedu.charging.account.pojo.param.WxLoginParam;
import cn.tedu.charging.account.pojo.vo.UserLoginResultVO;
import cn.tedu.charging.account.pojo.vo.UserStandardVO;
import cn.tedu.charging.account.service.IUserService;
import cn.tedu.charging.common.consts.HttpConsts;
import cn.tedu.charging.common.ex.ServiceException;
import cn.tedu.charging.utils.WxCryptUtils;
import cn.tedu.charging.web.JsonResult;
import cn.tedu.charging.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 处理用户相关请求的控制器类
 *
 * @author wyy
 * @version 1.0
 */
@RestController
@RequestMapping("/")
@Slf4j
public class UserController implements HttpConsts {

    @Value("${miniapp.wx.appId}")
    private String appId;

    @Value("${miniapp.wx.appSecret}")
    private String appSecret;

    @Autowired
    private IUserService service;

    @PostMapping("/wxLogin")
    public JsonResult wxTest(@RequestBody WxLoginParam wxLoginParam) {
       log.debug("开始处理【用户登录】的请求，参数：{}" ,wxLoginParam);
       StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?")
               .append("appid=" + this.appId)
               .append("&secret=" + this.appSecret)
               .append("&grant_type=authorization_code")
               .append("&js_code=" + wxLoginParam.getCode());

       RestTemplate restTemplate = new RestTemplate();
       ResponseEntity<String> response = restTemplate.exchange(requestUrl.toString(), HttpMethod.GET, new HttpEntity<String>(new HttpHeaders()), String.class);

       Map<String, String> body = (Map) JSON.parse(response.getBody());
       System.out.println(body);

       String sessionKey = body.get("session_key");
       String openId = body.get("openid");
       if (openId == null) {
           String message = "微信账号关联失败！";
           throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
       }
       String decrypt = WxCryptUtils.decrypt(sessionKey, wxLoginParam.getIv(), wxLoginParam.getEncryptedData());
       Map<String, Object> userInfo = (Map) JSON.parse(decrypt);

       UserStandardVO userStandardVO = service.getStandardByOpenId(openId);
       if (userStandardVO != null){
           UserLoginResultVO userLoginResultVO = service.login(openId);
           return JsonResult.ok("登陆成功！", userLoginResultVO);
       } else {
           UserLoginResultVO userLoginResultVO= service.sign(userInfo, openId);
           return JsonResult.ok("注册成功！", userLoginResultVO);
       }
    }

}
